local class = reload("class")
local clone = reload("table.opt.clone")
local source = reload("table.opt.source")
local cowork = reload("thread.work")
local cofork = reload("thread.fork")
local objecs = reload("global.objecs")

---@class super.basic @super.basic类
local this = class()

---构造函数
function this:ctor()
    ---标识自增
    local id = objecs.id or 0
    id = id + 1
    objecs.id = id

    ---对象注册
    local map = objecs.map
    map[id] = self
    ---记录标识
    self.id = id
end

---初始数据
function this:init()
end

---启动对象
function this:launch()
end

--数据清空
function this:clear()
end

--垃圾回收
function this:gcback()
    ---一处对象引用
    local id = self.id
    local map = objecs.map
    map[id] = nil
end

---数据拷贝
function this:clone()
    return clone(self)
end

---数据还原
---@param data table @还原数据
function this:source(data)
    return source(self, data)
end

---异步调用
function this:async(func, carg, ...)
    self.carg = carg
    local co = cowork()
    carg.co = co
    local ls = { self, carg, ... }
    ls.self = self
    ls.carg = carg
    co(func, ls)
end

---等待恢复
function this:await(...)
    return coroutine.yield(...)
end

---异步回调
function this:coback(carg, ...)
    carg.co(...)
end

---数据回调
function this:codata(data, key, ret)
    data[key] = ret
end

---延迟调用
function this:codelay(carg, ms)
    ---暂时只能放这里加载-不然死循环
    local delay = reload("timer.delayms")
    delay(self, carg, ms)
    self:await()
end

---协程结束
function this:coexit(carg)
    self.carg = nil
    carg.exit = true
end

---回收协程
function this:cofork(carg)
    cofork(carg)
end

---协程计数
function this:comark(carg, no)
    local counter = carg.counter or 0
    carg.counter = counter + 1
    if not no then
        return self:codefer(carg)
    end
end

---协程确认
function this:confirm(carg)
    local counter = carg.counter or 0
    carg.counter = counter - 1
    if 1 == counter then
        self:coback(carg)
    end
end

---延后确认
function this:codefer(carg)
    if not carg.clofirm then
        function carg.clofirm()
            self:confirm()
        end
    end
    return carg.clofirm
end

function this:reload()
end

return this
